package wk.demo.activities;

import android.app.AppOpsManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.Toast;

import com.luoye.bzijkplayer.R;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.io.IOException;

import wk.demo.callback.FileSelectCallback;
import wk.demo.config.WkConfig;
import wk.demo.fragments.FileListFragment;
import wk.demo.tool.FileTool;
import wk.demo.tool.WkLogTool;


public class FileExplorerActivity extends BashCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String rootDir=FileTool.getExternalSdPath().toString() ;


        String lastDirectory = MMKV.defaultMMKV().decodeString(WkConfig.KEY_LASTDIRCTORY) ;
        String dir ;
        if (!TextUtils.isEmpty(lastDirectory) && new File(lastDirectory).isDirectory()){
            dir = lastDirectory;
        }  else{
            dir= rootDir;
        }
        doOpenDirectory(dir ,false);

        setTtitleMsg("");
    }



    private void doOpenDirectory(String path, boolean addToBackStack) {
        if(path.equals("/storage/emulated")){
            path= "/storage/emulated/0" ;
            Toast.makeText(mcontext ,"已经是顶层了" ,Toast.LENGTH_SHORT).show();
        }

        Fragment newFragment = FileListFragment.newInstance(path ,fileSelectCallback);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.body, newFragment);

        if (addToBackStack){
            transaction.addToBackStack(null);
        }

        transaction.commit();
    }


    private FileSelectCallback fileSelectCallback = new FileSelectCallback() {
        @Override
        public void onSelect(File file) {

            if(file==null){
                return;
            }

            try {
                // 返回此抽象路径名的规范形式。
                file = file.getCanonicalFile();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (file.isDirectory()) {
                String path = file.toString();
                MMKV.defaultMMKV().encode(WkConfig.KEY_LASTDIRCTORY ,"") ;
                doOpenDirectory(path, true);
            } else if (file.exists()) {
                VideoActivity.intentTo(mcontext, file.getPath() );
            }
        }
    };



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            onKeyBackClick();
            return  true ;
        }else {
            return super.onKeyDown(keyCode, event);
        }

    }





}


